// Copyright 2023 Innkeeper Lukexp(王晓平) &lt;37196496@qq.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://gitee.com/jetxt/jinyu.

package response

import (
	"math"

	"github.com/gin-gonic/gin"
)

const (
	STATUSOK = 200
	SUCCESS  = 0
)

type Response struct {
	Code int         `json:"code"` //返回代码 0表示成功，大于0为错误代码
	Data interface{} `json:"data"` //返回数据集
	Msg  string      `json:"msg"`  //消息
}

type Pages struct {
	List      interface{} `json:"list"`
	Total     int         `json:"total"`
	Pagecount int         `json:"pagecount"`
}

func Result(code int, data interface{}, msg string, c *gin.Context) {
	c.JSON(STATUSOK, Response{
		Code: code,
		Data: data,
		Msg:  msg,
	})
}

func OK(c *gin.Context, data interface{}, msg string) {
	var res Response
	res.Code = SUCCESS
	if data != nil {
		res.Data = data
	}
	if msg != "" {
		res.Msg = msg
	}
	c.JSON(STATUSOK, res)
}

func Fail(c *gin.Context, code int, msg string) {
	var res Response
	res.Code = code
	if msg != "" {
		res.Msg = msg
	}
	c.JSON(STATUSOK, res)
}

func PageOK(c *gin.Context, list interface{}, total int, size int) {
	var pagecount int = 1
	if size > 0 {
		pagecount = int(math.Ceil(float64(total) / float64(size)))
	}
	var p = &Pages{
		List:      list,
		Total:     total,
		Pagecount: pagecount,
	}
	OK(c, p, "")
}

func Custom(c *gin.Context, data gin.H) {
	c.JSON(STATUSOK, data)
}

func PageNotFound(c *gin.Context) {
	data := map[string]string{"Error": "Page not found!"}
	c.JSON(404, data)
}
